package com.example.multitenant.multitenant.controller

import com.example.multitenant.multitenant.config.DataSources
import com.example.multitenant.multitenant.config.MultiTenantProperties
import com.example.multitenant.multitenant.config.TenantContext
import com.example.multitenant.multitenant.model.Tenant
import com.example.multitenant.multitenant.model.Tenants
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 * @author xiang
 * @Date 2022/9/15 9:29
 **/
@Service
class TenantService {

    @Autowired
    private lateinit var tenants: Tenants

    @Autowired
    private lateinit var dataSources: DataSources

    @Autowired
    private lateinit var tenantProperties: MultiTenantProperties

    @Transactional
    fun addTenant(groupId: String, dbName: String) {
        tenants.save(Tenant(groupId = groupId, dbName = dbName))
        dataSources.initTenantDataSources()
    }

    fun getTenants(): List<Tenant> {
        return tenants.findAll()
    }

    fun runOnAllTenants(run: () -> Unit) {
        TenantContext.setTenantId(tenantProperties.masterDb)
        tenants.findAll().forEach {
            TenantContext.setTenantId(it.dbName)
            run()
        }
    }


}